<template>
	<main-container class="goods-container">
		<div class="goods-info" style="padding: 20px" v-loading="loading">
			<el-form ref="formRef" class="form" :model="state.form" label-width="120px" :rules="state.rules" status-icon>
				<el-tabs v-model="active" class="goods-tabs">
					<el-tab-pane label="基本信息" :name="0">
						<el-form-item label="商品名称" prop="name">
							<el-input v-model="state.form.name"></el-input>
						</el-form-item>
						<el-form-item label="商品子标题" prop="subTitle">
							<el-input v-model="state.form.subTitle" maxlength="50" type="textarea" show-word-limit :rows="2"></el-input>
						</el-form-item>
						<el-form-item label="商品图" prop="spuUrls">
							<SelectMaterial
								v-model="state.form.spuUrls"
								:canChooseImagesNum="5"
							></SelectMaterial>
						</el-form-item>

						<el-row>
							<el-col :span="12">
								<el-form-item label="商品类目" prop="categoryIds">
									<el-cascader
										:options="state.categoryTreeList"
										v-model="state.form.categoryIds"
										clearable
										:props="defaultProps"
										@change="changeCategory"
									></el-cascader>
								</el-form-item>
								<el-form-item label="运费模板" prop="freightTemplateId">
									<el-select v-model="state.form.freightTemplateId" clearable >
										<el-option v-for="(item, index) in state.freightTemplateList" :key="index" :label="item.name" :value="item.id"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="商品状态" prop="status">
									<el-radio-group v-model="state.form.status">
										<el-radio label="0">下架</el-radio>
										<el-radio label="1">上架</el-radio>
									</el-radio-group>
								</el-form-item>
								<el-form-item label="商品销量" prop="salesVolume">
									<el-input-number v-model="state.form.salesVolume" :min="0" :precision="0" controls-position="right" />
								</el-form-item>
							</el-col>
						</el-row>
					</el-tab-pane>
					<el-tab-pane label="规格信息" :name="1">
						<!-- 多规格 -->
						<el-form-item label="多规格" prop="enableSpecs">
							<el-switch
								v-model="state.form.enableSpecs"
								inline-prompt
								active-value="1"
								inactive-value="0"
								active-text="是"
								inactive-text="否"
								@change="changeEnableSpecs"
							></el-switch>
						</el-form-item>
						<el-form-item label="多规格" v-if="state.form.enableSpecs == '1'">
							<div style="width: 100%">
								<Sku
									:specsListProp="state.specsList"
									:skusData="state.form.goodsSkus"
									:goodsSpuSpecs="state.goodsSpuSpecs"
									@getGoodsSkus="getGoodsSkus"
								></Sku>
							</div>
						</el-form-item>
						<el-row v-if="state.form.enableSpecs == '0'">
							<el-col :span="12">
								<el-form-item label="商品原价（元）" prop="sku.originalPrice">
									<el-input-number v-model="state.form.sku.originalPrice" :min="0.01" :precision="2" controls-position="right" />
								</el-form-item>
								<el-form-item label="商品成本价（元）" prop="sku.costPrice">
									<el-input-number v-model="state.form.sku.costPrice" :min="0.01" :precision="2" controls-position="right" />
								</el-form-item>
								<el-form-item label="一级分销比例" prop="sku.firstRate">
									<el-input-number v-model="state.form.sku.firstRate" :min="0" :precision="0" controls-position="right" />
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="商品售价（元）" prop="sku.salesPrice">
									<el-input-number v-model="state.form.sku.salesPrice" :min="0.01" :precision="2" controls-position="right" />
								</el-form-item>
								<el-form-item label="商品库存" prop="sku.stock">
									<el-input-number v-model="state.form.sku.stock" :min="0" :precision="0" controls-position="right" />
								</el-form-item>
								<el-form-item label="二级分销比例" prop="sku.secondRate">
									<el-input-number v-model="state.form.sku.secondRate" :min="0" :precision="0" controls-position="right" />
								</el-form-item>
							</el-col>
						</el-row>
					</el-tab-pane>
					<el-tab-pane label="商品详情" :name="2">
						<el-form-item label="商品描述" prop="description">
							<Editor v-model:get-html="state.form.description"  height="500px" :disable="false"></Editor>
						</el-form-item>
					</el-tab-pane>
				</el-tabs>
			</el-form>
			<div class="goods-footer">
				<div class="button">
					<el-button @click="handleClose">关 闭</el-button>
					<el-button @click="handleNext" v-if="active < 2"> 下一步 </el-button>
					<el-button type="primary" :disabled="loading" @click="submitForm(formRef)"> 确 认 </el-button>
				</div>
			</div>
		</div>
	</main-container>
</template>
<script lang="ts" setup>
import { defineAsyncComponent, ref, reactive } from 'vue';
import { addObj, editObj, getById } from '/@/api/product/goodsspu';
import { getList as getFreightTemplateList } from '/@/api/product/freighttemplate';
import { getPage as getCategoryTree } from '/@/api/product/goodscategory';
import { getList as getSpecsList } from '/@/api/product/goodsspecs';
import { getList as getGoodsSpuSpecs } from '/@/api/product/goodsspuspecs';
import { useRouter, useRoute } from 'vue-router';
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus';

const Editor = defineAsyncComponent(() => import('/@/components/editor/index.vue'));
const SelectMaterial = defineAsyncComponent(() => import('/@/components/selectMaterial/index.vue'));
const Sku = defineAsyncComponent(() => import('/@/components/sku/index.vue'));
interface DataState {
	form: {
		id: undefined;
		name: string;
		subTitle: string;
		spuUrls: Array<string>;
		salesVolume: number;
		enableSpecs: string;
		freightTemplateId: string;
		status: string;
		description: string;
		goodsSkus: Array<any>;
		goodsSpuSpecs: Array<any>;
		categoryFirstId: string;
		categorySecondId: string;
		sku: {
			originalPrice: number;
			costPrice: number;
			firstRate: number;
			salesPrice: number;
			stock: number;
			secondRate: number;
		};
		categoryIds: Array<string>;
	};
	rules: any;
	freightTemplateList: Array<any>;
	categoryTreeList: Array<any>;
	specsList: Array<any>;
	goodsSpuSpecs: Array<any>;
}
const active = ref(0);
const state = reactive<DataState>({
	form: {
		id: undefined,
		name: '',
		subTitle: '',
		spuUrls: [],
		salesVolume: 0,
		enableSpecs: '0',
		freightTemplateId: '',
		status: '1',
		description: '',
		goodsSkus: [],
		goodsSpuSpecs: [],
		categoryFirstId: '',
		categorySecondId: '',
		sku: {
			originalPrice: 0,
			costPrice: 0,
			salesPrice: 0,
			stock: 0,
			secondRate: 0,
			firstRate: 0,
		},
		categoryIds: [],
	},
	rules: {
		name: [
			{
				required: true,
				message: '请输入商品名称',
				trigger: 'change',
			},
		],
		spuUrls: [
			{
				required: true,
				message: '请上传商品图',
				trigger: 'change',
			},
		],
		status: [
			{
				required: true,
				message: '请选择商品状态',
				trigger: 'change',
			},
		],
		freightTemplateId: [
			{
				required: true,
				message: '请选择运费模板',
				trigger: 'change',
			},
		],
		categoryIds: [
			{
				required: true,
				message: '请选择商品类目',
				trigger: 'change',
			},
		],
		description: [
			{
				required: true,
				message: '请输入商品描述',
				trigger: 'change',
			},
		],
		'sku.originalPrice': [
			{
				required: true,
				message: '请输入商品原价（元）',
				trigger: 'change',
			},
		],
		'sku.salesPrice': [
			{
				required: true,
				message: '请输入商品销售价（元）',
				trigger: 'change',
			},
		],
		'sku.costPrice': [
			{
				required: true,
				message: '请输入商品成本价（元）',
				trigger: 'change',
			},
		],
		'sku.stock': [
			{
				required: true,
				message: '请输入商品库存数量',
				trigger: 'change',
			},
		],
	},
	freightTemplateList: [],
	categoryTreeList: [],
	specsList: [],
	goodsSpuSpecs: [],
});
const $route = useRouter();
const $useRoute = useRoute();
const loading = ref(false);
const formRef = ref();
const defaultProps = {
	label: 'name',
	value: 'id',
	children: 'children',
};

/**
 * 下一步
 */
const handleNext = () => {
	active.value++;
};
/**
 * 关闭事件
 */
const handleClose = () => {
	resetForm(formRef.value);
	$route.back();
};
/**
 * 重置表单
 */
const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	state.form = {
		id: undefined,
		name: '',
		subTitle: '',
		spuUrls: [],
		salesVolume: 0,
		enableSpecs: '0',
		freightTemplateId: '',
		status: '1',
		description: '',
		goodsSkus: [],
		goodsSpuSpecs: [],
		categoryFirstId: '',
		categorySecondId: '',
		sku: {
			originalPrice: 0,
			costPrice: 0,
			salesPrice: 0,
			stock: 0,
			secondRate: 0,
			firstRate: 0,
		},
		categoryIds: [],
	};
	loading.value = false;
	// formEl.resetFields();
};
/**
 * 提交按钮
 */
const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			// 单规格sku 处理
			if (state.form.enableSpecs === '0') {
				state.form.goodsSkus = [state.form.sku];
			}
			// 多规格sku 处理
			if (state.form.enableSpecs === '1') {
				if (state.form.goodsSpuSpecs && state.form.goodsSpuSpecs.length > 0) {
					state.form.goodsSpuSpecs[0].goodsSkuSpecsValues.forEach((item: any) => {
						item.picUrl = item.picUrls ? item.picUrls[0] : '';
					});
				}
			}
			loading.value = true;
			if (state.form.id) {
				//修改
				edit();
			} else {
				//新增
				add();
			}
		} else {
			ElMessage.success({
				message: '请完善商品信息',
				type: 'warning',
			});
		}
	});
};
/**
 * 新增
 */
const add = () => {
	addObj(state.form)
		.then((response) => {
			ElMessageBox.confirm('新增成功', '提示', {
				confirmButtonText: '继续添加',
				cancelButtonText: '返回列表',
				type: 'success',
			})
				.then(() => {
					resetForm(formRef.value);
				})
				.catch(() => {
					handleClose();
				});
		})
		.catch(() => {
			loading.value = false;
		});
};
/**
 * 修改
 */
const edit = () => {
	editObj(state.form)
		.then((response) => {
			ElMessageBox.confirm('修改成功', '提示', {
				confirmButtonText: '新增商品',
				cancelButtonText: '返回列表',
				type: 'success',
			})
				.then(() => {
					resetForm(formRef.value);
				})
				.catch(() => {
					handleClose();
				});
		})
		.catch(() => {
			loading.value = false;
		});
};
/**
 * 查询全部运费模板
 */
const getFreightTemplate = () => {
	getFreightTemplateList({}).then((response) => {
		state.freightTemplateList = response.data.data;
	});
};
/**
 * 查询全部商品类目
 */
const getCategory = () => {
	getCategoryTree().then((response) => {
		state.categoryTreeList = response.data.data;
	});
};

/**
 * 商品类目改变事件
 */
const changeCategory = (categoryIds: any) => {
	state.form.categoryFirstId = categoryIds[0];
	state.form.categorySecondId = categoryIds[1];
};

/**
 * 查询规格数据
 */
const getSpecs = () => {
	getSpecsList({}).then((response) => {
		state.specsList = response.data.data;
	});
};
/**
 * 多规格change事件 1.开始多规格；0.关闭多规格
 */
const changeEnableSpecs = (status: string) => {
	if (status == '1') {
		getSpecs();
	} else {
		if (!state.form.sku) {
			state.form.sku = {
				originalPrice: 0,
				costPrice: 0,
				salesPrice: 0,
				stock: 0,
				secondRate: 0,
				firstRate: 0,
			};
		}
	}
};
/**
 * 查询spu绑定的规格
 */
const getGoodsSpuSpecsList = (id: string) => {
	getGoodsSpuSpecs({ spuId: id }).then((response) => {
		let spuSpecList = response.data.data;
		if (spuSpecList && spuSpecList.length > 0) {
			spuSpecList[0].goodsSkuSpecsValues.forEach((item: any) => {
				item.picUrls = [item.picUrl];
			});
		}
		state.goodsSpuSpecs = spuSpecList;
	});
};
/**
 * 多规格组件回调事件
 */
const getGoodsSkus = (skus: any, goodsSpuSpecs: any) => {
	state.form.goodsSkus = skus;
	state.form.goodsSpuSpecs = goodsSpuSpecs;
};
const initForm = () => {
	const { id }: any = $useRoute.query;
	state.goodsSpuSpecs = [];
	getCategory();
	if (id) {
		loading.value = true;
		// 修改
		getById(id)
			.then((response) => {
				loading.value = false;
				state.form = response.data.data;
				state.form.categoryIds = [response.data.data.categoryFirstId, response.data.data.categorySecondId];
				if (response.data.data.enableSpecs == '1') {
					getSpecs();
				} else {
					state.form.sku = response.data.data.goodsSkus[0] ? response.data.data.goodsSkus[0] : {};
				}
				getGoodsSpuSpecsList(response.data.data.id);
			})
			.catch(() => {
				loading.value = false;
			});
	}
};

initForm();
getFreightTemplate();
</script>
<style lang="scss" scoped>
.goods-container {
	height: 100%;
	.goods-info {
		flex: 1;
		overflow: auto;
		.form {
			margin-bottom: 38px;
		}
		.goods-footer {
			position: absolute;
			bottom: 20px;
			left: 20px;
			right: 20px;
			background-color: #fff;
			border-top: 1px solid var(--next-color-danger-lighter);
			padding: 10px 16px;
			z-index: 9;
			display: flex;
			justify-content: center;
			align-items: center;
			.el-button {
				width: 100px;
			}
			.button {
				display: flex;
				justify-content: center;
			}
		}
	}
}
</style>
